<?php

namespace Addons\Weixin\Controller;
use Home\Controller\HomeController;
define('WEIXIN_INCLUDE_PATH', ONETHINK_ADDON_PATH . 'Weixin/Include');

class WeixinController extends HomeController
{
    protected $token;
    protected $data = array();
    protected $cfg; //插件配置信息

    public function _initialize()
    {
        parent::_initialize();
        $this->token = I('get.token');
    }

    /**
     * 微信返回数据处理方法
     **/
    public function index()
    {
        import('Wechat', WEIXIN_INCLUDE_PATH, '.class.php');
        import('fun', WEIXIN_INCLUDE_PATH, '.php');
        $addons = _get_addons('Weixin');
        $this->cfg = json_decode($addons['config'], true);
        if ($this->cfg['Token'] != I('get.token') || $addons['status'] != '1') die('false');
        $weixin = new \Wechat($this->token);
        $this->data = $weixin->request();
        list($content, $type) = $this->reply();
        $weixin->response($content, $type);
    }

    /**
     * 微信消息处理
     **/
    protected function  reply()
    {
        $data = $this->data;
        $list = M('custom')->order('srot')->select();

        foreach($list as $k=>$vo){
            $list[$k]['img'] = $this->getImg($vo['img']);
        }
        if ('subscribe' == $data['Event']) {
            $content = array();
            foreach($list as $k=>$v){
                $content[] = array($v['title'],"", $v['img'],$v['url']);
            }
            return array($content,'news');
        } //关注事件
        elseif ('unsubscribe' == $data['Event']) {
            return array('取消关注', 'text');
        } //取消关注事件
        elseif ('LOCATION' == $data['Event']) {
            die(' ');
            //return array('自动获取您的位置','text');
        } //自动上报地理位置
        elseif ('CLICK' == $data['Event']) {
            return array($data['EventKey'], 'text');
        } //菜单点击事件
        elseif ('LOCATION' == $data['Event']) {
            return array('自动获取您的位置', 'text');
        } //自动上报地理位置
        elseif ('VIEW' == $data['Event']) {
            return array($data['EventKey'], 'text');
        } //菜单跳转
        elseif ('voice' == $data['MsgType'] && !isset($data['Recognition'])) {
            return array('语音识别', 'text');
        } //语音消息
        elseif ('image' == $data['MsgType']) {
            return array('图片消息', 'text');
        } //图片消息
        elseif ('text' == $data['MsgType']) {
            $content[] = array($list[0]['title'],"", $list[0]['img'],$list[0]['url']);
            return array($content,'news');
        } //文字消息
        elseif ('location' == $data['MsgType']) {
            return array('地理位置消息', 'text');
        } //地理位置消息
        elseif ('link' == $data['MsgType']) {
            return array('链接消息', 'text');
        } //链接消息
        elseif ('video' == $data['MsgType']) {
            return array('视频消息', 'text');
        } //视频消息
        elseif ('voice' == $data['MsgType'] && isset($data['Recognition'])) {
            return array('语音识别结果：' . $data['Recognition'], 'text');
        } //语音识别
        else {
            die(' ');
        }
        //其它非识别
    }

    /**
     * 获取微信ACCESS_TOKEN
     **/
    protected function get_access_token()
    {
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $this->cfg['appID'] . '&secret=' . $this->cfg['appsecret'];
        $tmp = json_decode($this->curlGet($url), true);
        $access_token = $tmp['access_token'];
        return $access_token;
    }

    /**
     * curl get 数据
     **/
    protected function curlGet($url)
    {
        $ch = curl_init();
        $header = array("Accept-Charset: utf-8");
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        return curl_exec($ch);
    }

    /**
     * curl post 数据
     **/
    protected function https_post($url, $data)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($curl);
        if (curl_errno($curl)) {
            return 'Errno' . curl_error($curl);
        }
        curl_close($curl);
        return $result;
    }

    /**
     * 获取用户基本信息
     **/
    protected function get_user_info($openid)
    {
        $access_token = $this->get_access_token();
        $url = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token=' . $access_token . '&openid=' . $openid . '&lang=zh_CN';
        return json_decode($this->curlGet($url), true);
    }

    /**
     * 是否绑定平台用户
     **/
    protected function is_bind_user($openid = '')
    {
        $openid = $openid ? $openid : $this->openid;
        $weixin_user = M('weixin_users')->where(array('openid' => $openid))->find();
        return $weixin_user['uid'] > 0;
    }

    //获取图片URL
    public function getImg($id){
        $str = "http://" . $_SERVER["HTTP_HOST"];
        $info = M('picture')->where("id = $id")->find();
        $str = $str . $info['path'];
        return $str;
    }
}
